import cv2
import numpy as np
import matplotlib.pyplot as plt
import os

# 读取图片
image = cv2.imread('D:\shufa\hanzi1.jpg')

# 转换为灰度图
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 获取图片尺寸
height, width = gray_image.shape
# 设置窗口大小
window_width = 500
window_height = int(height * (window_width / width))
# 调整窗口大小以适应图片
cv2.namedWindow("Gray Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Gray Image", window_width, window_height)
# 显示灰度图
cv2.imshow("Gray Image", gray_image)

# 全局阈值处理
ret, binary_image = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY_INV)
# 设置窗口大小
window_width = 500
window_height = int(height * (window_width / width))
# 调整窗口大小以适应图片
cv2.namedWindow("Binary Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Binary Image", window_width, window_height)
# 显示二值化图
cv2.imshow("Binary Image", binary_image)

# 腐蚀操作
kernel = np.ones((9, 9), np.uint8)
eroded_image = cv2.erode(binary_image, kernel, iterations=1)
# 设置窗口大小
window_width = 500
window_height = int(height * (window_width / width))
# 调整窗口大小以适应图片
cv2.namedWindow("Eroded Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Eroded Image", window_width, window_height)
# 显示腐蚀后的图片
cv2.imshow("Eroded Image", eroded_image)

# 膨胀操作
kernel = np.ones((9, 9), np.uint8)
dilated_image = cv2.dilate(eroded_image, kernel, iterations=1)
# 中值滤波去除小白点
median_filtered_image = cv2.medianBlur(dilated_image, 9)
# 设置窗口大小
window_width = 500
window_height = int(height * (window_width / width))
# 调整窗口大小以适应图片
cv2.namedWindow("Processed Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Processed Image", window_width, window_height)
# 显示处理后的图片
cv2.imshow("Processed Image", median_filtered_image)

# 创建结构元素
kernel = np.ones((5, 5), np.uint8)
# 进行闭运算
closed_img = cv2.morphologyEx(dilated_image, cv2.MORPH_CLOSE, kernel, iterations=23)
# 设置窗口大小
window_width = 500
window_height = int(height * (window_width / width))
# 调整窗口大小以适应图片
cv2.namedWindow("Closed Image", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Closed Image", window_width, window_height)
# 显示闭运算的结果
cv2.imshow('Closed Image', closed_img)

# 等待按键，然后关闭窗口
cv2.waitKey(0)
cv2.destroyAllWindows()